//
//  CommitFileViewController.swift
//  GiteeClient
//
//  Created by 王志标 on 2020/10/28.
//

import UIKit
import WebKit
import PKHUD

/// 提交控制器中的文件展示控制器
class CommitFileViewController: UIViewController {

    
    var nameSpace:String!
    var diffModel:DiffModel!
    var commitModel:CommitModel!
    var contentWebView:WKWebView!
    
    var fileName:String!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        loadData()
    }
    
    init(model: DiffModel, commitM:CommitModel, nameSpace: String) {
        super.init(nibName: nil, bundle: nil)
        self.diffModel = model
        self.nameSpace = nameSpace
        self.commitModel = commitM
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        
        if self.diffModel!.new_path.contains("/") {
            self.fileName = self.diffModel!.new_path!.split(separator: "/").last!.description
        }else {
            self.fileName = self.diffModel!.new_path!
        }
        self.title = fileName
        
        let config = WKWebViewConfiguration()
        let script = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); "
        
        let userScript = WKUserScript(source: script, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        let wkuserConter = WKUserContentController()
        wkuserConter.addUserScript(userScript)
        config.userContentController = wkuserConter
        config.dataDetectorTypes = .all
        var frame = view.bounds
        frame.size.height -= Common.topHeight
        contentWebView = WKWebView(frame: frame, configuration: config)
        view.addSubview(contentWebView)
        
        if #available(iOS 13.0, *) {
            view.backgroundColor = Colors.backgroundColor
        } 
    }
    
    
    func render(html: String){
        
        let lang = fileName.split(separator: ".").last!.description
        let theme = "github"
        let formatPath = Bundle.main.path(forResource: "code", ofType: "html")
        let highlightJsPath = Bundle.main.path(forResource: "highlight.pack", ofType: "js")
        let themeCssPath = Bundle.main.path(forResource: theme, ofType: "css")
        let codeCssPath = Bundle.main.path(forResource: "code", ofType: "css")
        
        let lineNums = "true"
        let format = try! String.init(contentsOfFile: formatPath!, encoding: String.Encoding.utf8)
        let escapedCode = File.escapeHTML(html: html)
        let contentHtml = NSString.init(format: format as NSString, themeCssPath!,codeCssPath!,highlightJsPath!,lineNums,lang,escapedCode).description
      
        contentWebView.loadHTMLString(contentHtml , baseURL: Bundle.main.bundleURL)
    }
    
    func loadData() {
        
        HUD.show(.progress)
        DispatchQueue.global().async {
            
            var url = URLs.DETIAL_URL + self.nameSpace + "/repository/commits/" + self.commitModel!.id.description + "/blob"
            url += "?filepath=\(self.diffModel!.new_path.description)"
            
            let nameSpaceStr = self.nameSpace.replacingOccurrences(of: "/", with: "%2F")
            var content_url = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
            content_url = content_url!.replacingOccurrences(of: self.nameSpace, with: nameSpaceStr)
            
            let headers = ["Accept-Type":"text/plain"]
            let result:Result<String> = NetWorkTool.shared.getRequestDefault(url: content_url!,headers: headers)
            
            DispatchQueue.main.async {
                HUD.hide()
                if result.code == 0 {
                    self.render(html: result.data!)
                }else {
                    HUD.flash(.label(result.message), delay: 1.0)
                }
            }
        }
    }
    
}



